Diet plan performance [Sliding Window]

Time: O(N); Space: O(1); easy

A dieter consumes calories[i] calories on the i-th day. For every consecutive sequence of k days, they look at T, the total calories consumed during that sequence of k days: * If T < lower, they performed poorly on their diet and lose 1 point; * If T > upper, they performed well on their diet and gain 1 point; * Otherwise, they performed normally and there is no change in points.

Return the total number of points the dieter has after all calories.length days.

Notes:

  • The total points could be negative.

Example 1:

Input: calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3

Output: 0

Explaination:

  • calories[0], calories[1] < lower and

  • calories[3], calories[4] > upper,

  • total points = 0.

Example 2:

Input: calories = [3,2], k = 2, lower = 0, upper = 1

Output: 1

Explaination:

  • calories[0] + calories[1] > upper,

  • total points = 1.

Example 3:

Input: calories = [6,5,0,0], k = 2, lower = 1, upper = 5

Output: 0

Explaination:

  • calories[0] + calories[1] > upper,

  • calories[2] + calories[3] < lower,

  • total points = 0.

Notes:

  • 1 <= k <= len(calories) <= 10^5

  • 0 <= calories[i] <= 20000

  • 0 <= lower <= upper

Solution

Sliding Window Maintain the sum of a sliding window length of k.

[1]:
import itertools

class Solution1(object):
    def dietPlanPerformance(self, calories, k, lower, upper):
        """
        :type calories: List[int]
        :type k: int
        :type lower: int
        :type upper: int
        :rtype: int
        """
        total = sum(itertools.islice(calories, 0, k))
        result = int(total > upper) - int(total < lower)

        for i in range(k, len(calories)):
            total += calories[i] - calories[i-k]
            result += int(total > upper) - int(total < lower)

        return result
[2]:
s = Solution1()
calories = [1,2,3,4,5]
k = 1
lower = 3
upper = 3
assert s.dietPlanPerformance(calories, k, lower, upper) == 0

calories = [3,2]
k = 2
lower = 0
upper = 1
assert s.dietPlanPerformance(calories, k, lower, upper) == 1

calories = [6,5,0,0]
k = 2
lower = 1
upper = 5
assert s.dietPlanPerformance(calories, k, lower, upper) == 0